package com.example.games.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import com.elex.quefly.common.ndk.memorypresser.MemoryPressedBitmapFactory;

import android.content.res.AssetManager;
import android.graphics.Bitmap;

public class ResourceManager {
	// assets 文件管理
	private static AssetManager assetManager = GameHelper.getContext()
			.getAssets();

	/**
	 * 资源点用到的图
	 */
	private static HashMap<String, Bitmap> mapImgs = new HashMap<String, Bitmap>();

	/**
	 * 图标文件扩展名
	 */
	private static String ICON_DAT_EXT = ".png";
	/**
	 * 地图文件扩展名
	 */
	private static String MAPIMG_DAT_EXT = ".png";
	/**
	 * 地图图片文件路径
	 */
	private static String MAPIMG_DAT_PATH = "map";

	public static void loadGameResource() {
		// 加载地图用到图资源
		String[] datFilter;
		try {
			datFilter = getAssetsFiles(MAPIMG_DAT_PATH);
			for (String fileName : datFilter) {
				if (fileName.endsWith(MAPIMG_DAT_EXT)) {
					loadMapImgs(fileName.substring(0,
							fileName.indexOf(ICON_DAT_EXT)));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("Resource load error!");
		}

	}

	private static String[] getAssetsFiles(String dir) throws IOException {
		return assetManager.list(dir);
	}

	/**
	 * 加载本地地图图片资源文件
	 * 
	 * @param index
	 */
	private static void loadMapImgs(String name) {
		try {
			if (mapImgs.containsKey(name)) {
				return;
			}
			InputStream is = null;
			is = loadLastResStream(MAPIMG_DAT_PATH + "/" + name
					+ MAPIMG_DAT_EXT);
			mapImgs.put(name, MemoryPressedBitmapFactory.decodeStream(is));
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Resource load error on mapimgs!");
		}
	}

	/**
	 * 载入最新的资源数据流
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	private static InputStream loadLastResStream(String filePath)
			throws IOException {
		return assetManager.open(filePath);
	}

	/**
	 * 获取地图背景用到的图
	 * 
	 * @param index
	 * @return
	 */
	public static Bitmap getMapImg(String name) {
		return mapImgs.get(name);
	}
}
